// 3.10 设置远程ICECandidates
use reqwest::Client;
use serde::{Deserialize};
use crate::api::get_session_id::get_session_id;
use crate::api::get_stream_token::get_stream_token;
use webrtc::{ice_transport::ice_candidate::RTCIceCandidateInit};
use anyhow::{Result, anyhow};
use webrtc::peer_connection::RTCPeerConnection;

#[derive(Debug, Deserialize)]
struct IceQueryResponse {
    exchangeResponse: String
}
#[derive(Debug, Deserialize)]
struct IceCandidateInit {
    candidate: String,
    sdpMid: Option<String>,
    sdpMLineIndex: Option<u16>,
}

pub async fn get_ice(peer_connection: &RTCPeerConnection) -> Result<()> {
    let client = Client::new();
    let session_id = get_session_id(None).await?;
    let stream_token = get_stream_token().await?;
    let authorization = format!("Bearer {}", stream_token);
    let url = format!(
        "https://xhome.gssv-play-prod.xboxlive.com/v5/sessions/home/{}/ice",
        session_id
    );

    let response = client
        .get(url)
        .header("Content-Type", "application/json")
        .header("Authorization", authorization)
        .send()
        .await?;

    if response.status().as_u16() != 200 {
        return Err(anyhow!(
            "failed to get ice candidates, response status: {}",
            response.status().as_u16()
        ));
    }

    let response: IceQueryResponse = serde_json::from_str(&response.text().await?)?;
    let exchange_response = response.exchangeResponse;
    println!("exchangeResponse: {}", exchange_response);

    let ice_candidates: Vec<IceCandidateInit> = serde_json::from_str(&exchange_response)?;

    for ice_candidate in ice_candidates {
        // 跳过 end-of-candidates 标志
        if ice_candidate.candidate.contains("end-of-candidates") {
            continue;
        }

        // 清理掉 "a=" 前缀
        let cleaned_candidate = ice_candidate
            .candidate
            .trim()
            .trim_start_matches("a=")
            .to_string();

        // 跳过明显无效的 candidate
        if cleaned_candidate.len() < 20 {
            println!("跳过无效 candidate: {}", cleaned_candidate);
            continue;
        }

        let candidate = RTCIceCandidateInit {
            candidate: cleaned_candidate,
            sdp_mid: ice_candidate.sdpMid.clone(),
            sdp_mline_index: ice_candidate.sdpMLineIndex,
            ..Default::default()
        };

        // 安全添加 candidate
        if let Err(e) = peer_connection.add_ice_candidate(candidate).await {
            println!("添加 candidate 失败: {:?}", e);
        }
    }

    Ok(())
}